/**
 * All Rights Reserved , Copyright (C) 2022 , 青岛鼎信通讯股份有限公司
 * <p>
 * MpmCommentsController
 * 评论表
 * <p>
 * 修改纪录
 * 2022-05-07 版本：1.0 mengmeng 创建。
 *
 * @version 版本：1.0
 * @author 作者：mengmeng
 * 创建日期：2022-05-07
 */

package com.topscomm.mpm.controller;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboDeptEntity;
import com.topscomm.cbo.pojo.CboOrgEntity;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.ICboMessageAppService;
import com.topscomm.cbo.service.ICboMessageSysService;
import com.topscomm.cbo.service.ICboUserService;
import com.topscomm.main.hessian.IBaseOperateRecordService;
import com.topscomm.mis.service.IMisDeptHeaderService;
import com.topscomm.mpm.MpmSystemConst;
import com.topscomm.mpm.controller.auto.MpmCommentsControllerAuto;
import com.topscomm.mpm.pojo.*;
import com.topscomm.mpm.service.IMpmProjectMilepostService;
import com.topscomm.mpm.service.IMpmProjectService;
import com.topscomm.mpm.service.IMpmProjectTaskService;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.Page;
import com.topscomm.pub.vo.ResponseResult;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: mengmeng
 * @date: 2022-05-07
 * @description:评论表Controller
 * @modify:
 */
@RestController
@RequestMapping("mpm/comments")
public class MpmCommentsController extends MpmCommentsControllerAuto implements IMpmCommentsController {

    @Autowired
    private IBaseOperateRecordService baseOperateRecordService;

    @Autowired
    private IMpmProjectService mpmProjectService;
    @Autowired
    private IMpmProjectTaskService mpmProjectTaskService;
    @Autowired
    private IMisDeptHeaderService misDeptHeaderService;
    @Autowired
    private ICboUserService cboUserService;
    @Autowired
    private IMpmProjectMilepostService mpmProjectMilepostService;

    /**
     * @author: mengmeng
     * @date: 2022-05-07
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    protected String spellListSql(Map<String, Object> paraMap) {
        StringBufferProxy sql = new StringBufferProxy();
        sql.appendSingle(" 1=1 ");
        if (paraMap.containsKey("qry_name")) {
            String value = paraMap.get("qry_name").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and name like '%{0}%' ", value);
        }
        if (paraMap.containsKey("qry_code")) {
            String value = paraMap.get("qry_code").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and code = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_sourceType")) {
            String value = paraMap.get("qry_sourceType").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and sourcetype = '{0}' ", value);
        }
        if (paraMap.containsKey("qry_sourceId")) {
            String value = paraMap.get("qry_sourceId").toString();
            if (!StringUtil.isEmpty(value))
                sql.appendSingle(" and sourceid = '{0}' ", value);
        }
        return sql.toString();
    }

    /**
     * @author: mengmeng
     * @date: 2022-05-07
     * @param paraMap
     * @return
     * @description:转换出查询SQL语句
     * @modify:
     */
    @Override
    @GetMapping(value = "/refList")
    public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
        return super.refList(paraMap);
    }

    @GetMapping(value = "/queryCommentList")
    public ResponseResult<Object> queryCommentList(@RequestParam(required = false) Map<String, Object> paraMap) {
        try {
            String sourceType = ConvertUtil.convertToString(paraMap.get("qry_sourceType"));
            String sourceId = ConvertUtil.convertToString(paraMap.get("qry_sourceId"));
            boolean qrySelf = ConvertUtil.convertToBoolean(paraMap.get("qry_self"));
            boolean qryRecord = ConvertUtil.convertToBoolean(paraMap.get("qry_record"));
            CboUserEntity currentUser = getUserBean().getUser();
            if (qrySelf) {
                paraMap.put("userCode", currentUser.getCode());
            }
            List<Map<String, Object>> mapList = this.service.queryBySourceTypeAndSourceId(sourceType, sourceId, paraMap);

			CboDeptEntity dept = getUserBean().getDept();
			CboOrgEntity org = getUserBean().getOrg();
            List<String> sourceIdList = readRecord(currentUser, mapList, dept, org);

            // 查询阅读记录
            if (qryRecord) {
                queryRecord(sourceIdList, mapList);
            }
            Page page = new Page(mapList, 0, 0, 0);
            return ResponseResult.ok(page);
        } catch (Exception var7) {
            return this.handleControllerException(var7);
        }
    }

    /**
     * @Description: 记录阅读记录
     * @Author: mengmeng
     * @Date: 2022/5/10 10:12
     * @Version: 1.0
     */
    private List<String> readRecord(CboUserEntity currentUser, List<Map<String, Object>> mapList, CboDeptEntity dept, CboOrgEntity org) {
        if (CollectionUtils.isEmpty(mapList)) {
            return new ArrayList<>();
        }
        List<String> sourceIdList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
        	if (!map.containsKey("list")) {
        		continue;
			}
            List<MpmCommentsEntity> commentList = (List<MpmCommentsEntity>) map.get("list");
            if (CollectionUtils.isEmpty(commentList)) {
                continue;
            }
            sourceIdList.addAll(commentList.stream().map(MpmCommentsEntity::getId).map(ConvertUtil::convertToString).collect(Collectors.toList()));
        }
		if (CollectionUtils.isEmpty(sourceIdList)) {
			return new ArrayList<>();
		}
        baseOperateRecordService.insertOperateRecord(MpmCommentsEntity.tableName, sourceIdList, MpmSystemConst.BaseOperateTypeEnum.View, currentUser.getCode(), currentUser.getName(), dept.getCode(), org.getCode());
		return sourceIdList;
    }

    private void queryRecord(List<String> sourceIdList, List<Map<String, Object>> mapList) {
        if (CollectionUtils.isEmpty(mapList) || CollectionUtils.isEmpty(sourceIdList)) {
            return;
        }
        Map<String, Object> param = new HashMap<>();
        param.put("sourceType", MpmCommentsEntity.tableName);
        param.put("sourceIdList", sourceIdList);
        param.put("operateType", MpmSystemConst.BaseOperateTypeEnum.View);
        List<Map<String, Object>> recordList = this.service.queryMap(param, "selectOperateRecordByParam");
        if (CollectionUtils.isEmpty(recordList)) {
            return;
        }
        Map<String, Map<String, Object>> recordMap = recordList.stream().collect(Collectors.toMap(item -> ConvertUtil.convertToString(item.get(BaseOperateRecordEntity.FieldSourceid)) + "_" + ConvertUtil.convertToString(item.get(BaseOperateRecordEntity.FieldUsercode)), item -> item, (v1, v2) -> v1));

        for (Map<String, Object> map : mapList) {
            if (!map.containsKey("list")) {
                continue;
            }
            List<MpmCommentsEntity> commentList = (List<MpmCommentsEntity>) map.get("list");
            if (CollectionUtils.isEmpty(commentList)) {
                continue;
            }
            String ceoCode = ConvertUtil.convertToString(map.get("ceoCode"));
            String managerCode = ConvertUtil.convertToString(map.get("managerCode"));
            List<Map<String, Object>> list = new ArrayList<>();
            for (MpmCommentsEntity entity : commentList) {
                Map<String, Object> tempMap = entity.convertToMap();
                tempMap.put("ceorecord",  recordMap.get(entity.getId() + "_" + ceoCode));
                tempMap.put("managerrecord",  recordMap.get(entity.getId() + "_" + managerCode));
                list.add(tempMap);
            }
            map.put("list", list);
        }
    }
}

